﻿
using System.Data;
using System.Text;

namespace Patent.Json
{
    public class JsonSerializer
    {
        public static string Serialize(DataTable table)
        {
            StringBuilder json = new StringBuilder();
            json.Append("[");
            for (int i = 0; i < table.Rows.Count; i++)
            {
                DataRow row = table.Rows[i];
                json.Append("{");
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    string columnName = table.Columns[j].ColumnName;
                    string columnType = table.Columns[j].DataType.Name;
                    if (columnType == "Int32" || columnType == "Int16" || columnType == "Decimal")
                    {
                        json.AppendFormat("\"{0}\":\"{1}\"", columnName, row.IsNull(columnName) ? "" : row[columnName]);
                    }
                    else if (columnType == "Boolean")
                    {
                        json.AppendFormat("\"{0}\":{1}", columnName, row.IsNull(columnName) ? "" : row[columnName].ToString().ToLower());
                    }
                    else
                    {
                        json.AppendFormat("\"{0}\":\"{1}\"", columnName, row[columnName]);
                    }

                    if (j < table.Columns.Count - 1) json.Append(",");
                }
                json.Append("}");

                if (i < table.Rows.Count - 1) json.Append(",");
            }
            json.Append("]");
            return json.ToString();
        }
    }
}

